package cn.xiqi.cms.hibernate.DAO;

import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import cn.xiqi.cms.hibernate.beans.Metadata;

public class DataDAOImpl implements DataDAO {

	@Override
	public int insert(Metadata record) {
		Session session = null;
		Transaction tx = null;
		int id = 0;
		
		try {
			session = HibernateSessionFactory.currentSession();
			tx = session.beginTransaction();
			session.save(record);
			id = record.getDataID();
			tx.commit();
		}
		catch (HibernateException e){
			throw e;
		}
		finally {
			if(tx!=null){
				tx.rollback();
			}
			HibernateSessionFactory.closeSession();
		}
		return id;
	}

	@Override
	public boolean delete(Metadata record) {
		Session session = null;
		Transaction tx = null;
		boolean b = true;
		
		try {
			session = HibernateSessionFactory.currentSession();
			tx = session.beginTransaction();
			session.delete(record);
			tx.commit();
		}
		catch (HibernateException e) {
			b = false;
			throw e;
		}
		finally {
			if(tx!=null) {
				tx.rollback();
			}
			HibernateSessionFactory.closeSession();
		}
		return b;
	}

	@Override
	public boolean update(Metadata record) {
		Session session = null;
		Transaction tx = null;
		boolean b =true;
		
		try {
			session = HibernateSessionFactory.currentSession();
			tx = session.beginTransaction();
			session.update(record);
			tx.commit();
		}
		catch (HibernateException e){
			b = false;
			throw e;
		}
		finally {
			if(tx!=null){
				tx.rollback();
			}
			HibernateSessionFactory.closeSession();
		}
		return b;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Metadata> select(Map<String, Object> values) {
		Session session = null;
		List<Metadata> records = null;
		Query query = null;
		String type;
		int page = 0;
		int size = 0;
		
		try {
			session = HibernateSessionFactory.currentSession();
			type = (String)values.get("type");
			if(type.equals("id")){
				query = session.createQuery("from Metadata where dataID=?");
				query.setInteger(0, (Integer)values.get("id"));
			}else if(type.equals("cate")) {
				query = session.createQuery("from Metadata where cate=?");
				query.setString(0, (String)values.get("cate"));
			}else if(type.equals("all")) {
				query = session.createQuery("from Metadata");
			}
			if(values.get("page") != null && (int)values.get("page") != 0 ){
				page = (int)values.get("page");
				size = (int)values.get("size");
				query.setFirstResult((page - 1) * size);
				query.setMaxResults(size);
			}
		}catch (Exception e) {
			throw e;
		} finally {
			records = query.list();
			HibernateSessionFactory.closeSession();
		}
		return records;
	}

}
